package com.aispeech.runner;

import com.aispeech.task.common.data.constant.Progress;
import com.aispeech.task.common.data.domain.Task;
import com.aispeech.task.common.data.enums.APICode;
import com.aispeech.task.common.exceptions.TaskException;
import com.aispeech.task.common.handler.TaskManager;
import com.aispeech.task.common.utils.TaskUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
public class LocalTaskManager implements TaskManager {
    @Override
    public void updateProgress(Task task, int progress) throws TaskException {
        task.setProgress(progress);
        log.info("[ updateProgress ] task: {}, progress: {}", TaskUtils.field(task.getId(), task.getProductId()), progress);
    }

    @Override
    public void finishTask(Task task, List<Map> result) throws TaskException {
        task.getMetrics().put("ts_finished", System.currentTimeMillis());
        task.setProgress(Progress.FINISHED);
        task.setFinished(true);
        task.setResult(result);

        log.info("[ finishTask ] task: {}", TaskUtils.field(task.getId(), task.getProductId()));

        ObjectMapper mapper = new ObjectMapper();
        try {
            log.info("[ finishTask ] detail: {}", mapper.writerWithDefaultPrettyPrinter().writeValueAsString(task));
        } catch (JsonProcessingException e) {
            throw new TaskException(e.getMessage());
        }
    }

    @Override
    public void breakTask(Task task, APICode code) throws TaskException {
        breakTask(task, code.getCode(), code.getMessage());
    }

    @Override
    public void breakTask(Task task, int code, String message) throws TaskException {
        task.updateError(code, message);

        task.getMetrics().put("ts_finished", System.currentTimeMillis());
        task.setFinished(true);

        log.error("[ breakTask ] task: {}, error: {} - {}", TaskUtils.field(task.getId(), task.getProductId()), code, message);
    }
}
